"use client";
import React, { useEffect, useState } from "react";
import { useRouter } from "@/utils/router";
import { fetchApi, fetchWithAuth } from "@/request/request";
import { showToast } from "@/components/ui/toast";
import { Mainbar } from "@/components/NavBar/mainBar";
import { Plus } from "lucide-react";


interface allPost {
    id: string;
    _id: string;
    title: string;
    cover: string;
}


export default function Collect() {
    const router = useRouter()
    const [collect, setCollect] = useState<allPost[]>([])
    const [MyCollect, setMyCollect] = useState<allPost[]>([])
    const [file, setFile] = useState<File | null>(null);
    //初始化
    useEffect(() => {
        fetchWithAuth("/api/auth/collect", { action: "init" }).then((res: any) => {
            setCollect(res.data.collect || [])
            setMyCollect(res.data.myCollect || [])
        })

    }, ["chat_id"]);

    const handleFileChange = (event: React.ChangeEvent<HTMLInputElement>) => {
        const selectedFile = event.target.files ? event.target.files[0] : null;

        if (selectedFile) {
            // 验证文件类型，只允许 .txt 和 .docx 文件
            const fileExtension = selectedFile.name.split('.').pop()?.toLowerCase();
            if (fileExtension === 'txt' || fileExtension === 'docx') {
                setFile(selectedFile);
            } else {
                showToast("仅支持上传 Word (.docx) 和 TXT (.txt) 文件");
                setFile(null); // 清除文件选择
            }
        }
    };


    // 处理文件上传
    const handleUpload = async () => {
        if (!file) {
            showToast("请选择一个文件！");
            return;
        }
        const user = localStorage.getItem("user") || null

        if (!user) {
            showToast("请先登录！");
            return;
        }
        try {
            const id = JSON.parse(user).id
            const formData = new FormData();
            formData.append('file', file);
            formData.append('id', id);
            console.log(formData)

            fetch('/api/upload', {
                method: 'POST',
                body: formData,
            })
                .then((res) => res.json())
                .then((res) => {
                    // console.log(res)
                    if (res.message == 'success') {
                        showToast("上传成功！")
                        setFile(null)
                    }
                });
        } catch (error) {
            // setFile(null)
            showToast("上传失败！");
            console.error("文件上传失败:", error);
        }
    };
    return (
        <>
            <div>
                <Mainbar />
            </div>
            <div className="w-full h-full mx-auto max-w-7xl pt-25 rounded-lg">
                <div className="relative mx-10 p-2 rounded-lg mb-5 max-w-7xl">
                    {/* <div className="mx-2 text-lg font-bold text-black inline-flex items-center">
                        我上传的
                        <Plus size={20} className="ml-2 border-2 border-[#090909] hover:border-blue-500 hover:text-blue-500 " />
                    </div> */}
                    <div className="mx-2 text-lg font-bold text-black inline-flex items-center">
                        我上传的
                        <label htmlFor="file-upload" className="ml-2 cursor-pointer">
                            <Plus size={20} className="border-2 border-[#090909] hover:border-blue-500 hover:text-blue-500" />
                        </label>
                        <input
                            id="file-upload"
                            type="file"
                            accept=".txt,.docx"
                            className="hidden"
                            onChange={handleFileChange}
                        />
                    </div>
                    {/* 滚动容器 */}
                    <div className="overflow-x-auto flex space-x-4 pl-4 custom-scrollbar-hide">
                        {MyCollect.length > 0 ? (<>
                            {MyCollect.map((e) => (
                                <div key={e._id} onClick={() => { router.push(`/reader/${e._id}`) }} className="flex flex-col items-center space-y-2">
                                    <div className="w-30 h-40 rounded-lg flex-shrink-0">
                                        <img
                                            className="w-30 h-40 object-cover rounded-lg"
                                            src={e.cover || ""}
                                            alt={e.title || "未知"}
                                        />
                                    </div>
                                    <div className="text-lg font-medium text-ellipsis overflow-hidden whitespace-nowrap w-30">
                                        {e.title}
                                    </div>
                                </div>
                            ))}</>) : (<>
                                <div className="flex flex-col items-center">
                                    <label htmlFor="file-upload">
                                        <div className="w-30 h-40 bg-[#ffffff] rounded-lg mt-2 flex items-center justify-center">
                                            <Plus size={50} />
                                        </div>
                                    </label>
                                </div>
                            </>)}
                    </div>

                    {/* 浮窗 */}
                    {file && (
                        <div className="fixed inset-0 flex justify-center items-center bg-transparent bg-opacity z-50">
                            <div className="bg-white p-6 rounded-lg shadow-lg sm:w-full md:w-1/3">
                                <div className="text-lg font-bold text-center">文本上传</div>
                                <div className="flex items-center space-x-2 mt-2">
                                    <p>文件:</p>
                                    <input
                                        type="text"
                                        value={file.name}
                                        onChange={(e) => setFile({ ...file, name: e.target.value })}
                                        className="px-2 py-1 border rounded-md  w-[70%]"
                                    />
                                </div>

                                {/* 按钮容器 */}
                                <div className="mt-4 flex justify-center gap-4">
                                    {/* 上传按钮 */}
                                    <button
                                        onClick={handleUpload}
                                        className="px-4 py-2 bg-black text-white rounded-md hover:bg-[#4c4c4c]"
                                    >
                                        上传
                                    </button>

                                    {/* 关闭按钮 */}
                                    <button
                                        onClick={() => { setFile(null) }}
                                        className="px-4 py-2 bg-gray-300 text-black rounded-md hover:bg-gray-400"
                                    >
                                        关闭
                                    </button>
                                </div>

                            </div>
                        </div>
                    )}

                </div>
                <div>
                    <div className="mx-12 text-lg font-bold text-black inline-flex items-center">
                        我的收藏</div>
                    <div className="flex items-center justify-center gap-4">
                        {collect.length != 0 ? (<>
                            {
                                collect.map((item, index) => {
                                    return (
                                        <div key={index} className="mx-5 mb-5" onClick={() => { router.push(`/reader/${item._id}`) }}>
                                            <div className="w-[7rem] h-40  rounded-lg">
                                                <img className="w-full h-auto object-cover rounded-lg" src={item.cover} alt={item.title} />
                                            </div>
                                            <span
                                                className="block text-ellipsis overflow-hidden whitespace-nowrap w-[7rem]"
                                                title={item.title}  // 添加 title 属性
                                            >
                                                {item.title}
                                            </span>
                                        </div>
                                    )
                                })
                            }</>) : (<>
                                <div>
                                    <div className="mx-auto px-2 rounded-lg w-[100px] text-[#ffffff] bg-[#181818] text-center text-2xl hover:bg-[#4c4c4c]" onClick={() => { router.push("/") }}>
                                        去收藏
                                    </div>
                                    <div className="mt-2 text-center text-2xl">还没有添加到书籍喔</div>
                                </div>
                            </>)}
                    </div>

                </div>

            </div>
        </>
    )
}